<?php
namespace Common\Utils;
class Revenue{
	public $gs_nead_row	=	array(
								'nsrsbh' =>array('纳税人识别号','nsrsbh'),
								'nsrmc'  =>array('纳税人名称','nsrmc'),
								'zsxm'   =>array('征收项目','zsxm_dm'),
								'se'     =>array('实缴金额','se'),
								'rkrq'   =>array('入库日期','rkrq'),
							);
	public $ds_nead_row	=	array(
								'nsrsbh' =>array('纳税人识别号','nsrsbh'),
								'nsrmc'  =>array('纳税人名称','nsrmc'),
								'zsxm'   =>array('征收项目','zsxm'),
								'se'     =>array('实缴金额','se'),
								'rkrq'   =>array('入库日期','rkrq'),
							);
	public $ds_file_path="dsrkxx/";

	public $gs_file_path="gsrkxx/";

	public $_err="";


	public function __construct()
	{
		$this->ds_file_path=C("excel_file_path").$this->ds_file_path;
		$this->gs_file_path=C("excel_file_path").$this->gs_file_path;
	}


	/**
	 * 将文件夹下的所有文件都导入到mysql中
	 * @return [type] [description]
	 */
	public function moreFileToMysql()
	{
		$files=scandir($this->ds_file_path);
		foreach($files as $file)
		{
			if($file=='.' || $file=='..') continue;

			if($this->dsoneFileToMysql($file))
			{
				echo "\r\n <=======文件:$file 数据导入完成======>\r\n";
			}
		}

		$files=scandir($this->gs_file_path);
		foreach($files as $file)
		{
			if($file=='.' || $file=='..') continue;

			if($this->gsoneFileToMysql($file))
			{
				echo "\r\n <=======文件:$file 数据导入完成======>\r\n";
			}
		}

	}
/**
 * 从一个csv文件中把数据导入到mysql中
 * @param  [type] $file_name [description]
 * @return [type]            [description]
 */
	public function dsoneFileToMysql($file_name)
	{
		
		$md_comlist=D("ComList");
		$md_revenue=D("Revenue");


		$file=$this->ds_file_path.$file_name;


		$group_key=DO_GROUP_KEY;


		if(!file_exists($file))
		{
			echo "$file 文件不存在!";
			return false;
		}

		$f = fopen($file,"r");
		$i=0;



		while(! feof($f))
		{
			$row=fgetcsv($f);
			$row=array_map(array($this, 'iconv_str'), $row);



			$i++;
			if($i==1)
			{
				//解析表头
				$row_key=$this->findRowKey($row,$this->ds_nead_row);
				continue;
			}

			if(!is_array($row_key))
			{
				echo "表头解析失败".$this->_err;
				return false;
			}

			$data_row=array(
				'row_number'=>$i,
				'group_key'=>$group_key,
			);
			//表头处理完毕.开始处理内容
			foreach($row_key as $key=>$row_num)
			{
				$data_row[$key]=$row[$row_num];
			}

			if(empty($data_row['nsrsbh']) && empty($data_row['nsrmc'])) continue;

			$data_row['csv_data']=serialize($row);

			//先记录企业信息
			$mssql_comid=$md_comlist->add_new($data_row['nsrsbh'],$data_row['nsrmc']);


			if(!empty($mssql_comid))
			{
				$data_row['mssql_comid']=$mssql_comid;
			}
			else
			{
				$this->saveNotFindCompany(array('nsrsbh'=>'~'.$data_row['nsrsbh'],'nsrmc'=>$data_row['nsrmc']));
			}

			$data_row['source']='ds';


			$state=$md_revenue->addNewData($data_row);
			if($state!=false)
			{
				echo "第 $i 行数据添加完成!\r\n";
			}
			else
			{
				echo "第 $i 行数据添加失败!\r\n";
			}
			unset($row);
		}
		fclose($f);
		unset($f);
		unset($md_revenue);
		unset($md_comlist);
		return true;
	}


	public function gsoneFileToMysql($file_name)
	{
		
		$md_comlist=D("ComList");
		$md_revenue=D("Revenue");

		$file=$this->gs_file_path.$file_name;

		$group_key=DO_GROUP_KEY;


		if(!file_exists($file))
		{
			echo "$file 文件不存在!";
			return false;
		}

		$f = fopen($file,"r");
		$i=0;
		while(! feof($f))
		{
			$row=fgetcsv($f);

			$row=array_map(array($this, 'iconv_str'), $row);

			$i++;
			if($i==1)
			{
				//解析表头
				$row_key=$this->gsfindRowKey($row);
				$ysfpbl_dm=$this->gsfindRowKey($row,'YSFPBL_DM');
				continue;
			}

			if(!is_array($row_key))
			{
				return false;
			}

			if($row[$ysfpbl_dm]=='中央100%') continue;

			$data_row=array(
				'row_number'=>$i,
				'group_key'=>$group_key,
			);
			//表头处理完毕.开始处理内容
			foreach($row_key as $key=>$row_num)
			{
				$data_row[$key]=$row[$row_num];
			}
			if(empty($data_row['nsrsbh']) && empty($data_row['nsrmc'])) continue;
			
			$data_row['csv_data']=serialize($row);

			//先记录企业信息
			$md_comlist->add_new($data_row['nsrsbh'],$data_row['nsrmc']);

			$mssql_comid=$md_comlist->add_new($data_row['nsrsbh'],$data_row['nsrmc']);

			if(!empty($mssql_comid))
			{
				$data_row['mssql_comid']=$mssql_comid;
			}
			else
			{
				$this->saveNotFindCompany(array('nsrsbh'=>'~'.$data_row['nsrsbh'],'nsrmc'=>$data_row['nsrmc']));
			}

			$data_row['source']='gs';
			$state=$md_revenue->addNewData($data_row);
			if($state!=false)
			{
				echo "第 $i 行数据添加完成!\r\n";
			}
			else
			{
				echo "第 $i 行数据添加失败!\r\n";
			}
			
			unset($data_row);
		}
		fclose($f);
		unset($f);
		unset($md_revenue);
		unset($md_comlist);
		return true;
	}

	/**
	 * 根据表头查询各内容列的列号
	 * @param  [type] $one_row [description]
	 * @return [type]          [description]
	 */
	protected function gsfindRowKey($one_row,$find_v=null)
	{
		$row_key=array();
		foreach($one_row as $key=>$v)
		{
			$v=strtolower($v);

			if(!empty($find_v))
			{

				if($v==strtolower($find_v)) return $key;
			}
			else
			{
				foreach($this->gs_nead_row as $nead_key=>$nead_v)
				{
					if(in_array($v, $nead_v))
					{
						$row_key[$nead_key]=$key;
						continue;
					}

				}
			}

			
		}

		if(count($row_key)==count($this->gs_nead_row))
		{
			return $row_key;
		}
		else
		{
			$this->_err="数据列不全";
			return false;
		}


		
		
		//print_r($row_key);
				
		//die();
	}


	/**
	 * 根据表头查询各内容列的列号
	 * @param  [type] $one_row [description]
	 * @return [type]          [description]
	 */
	protected function findRowKey($one_row,$nead_row)
	{
		$row_key=array();
		foreach($one_row as $key=>$v)
		{
			
			$v=strtolower($v);
			foreach($nead_row as $nead_key=>$nead_v)
			{
				if(in_array($v, $nead_v))
				{
					$row_key[$nead_key]=$key;
					continue;
				}

			}
		}

		if(count($row_key)==count($nead_row))
		{
			return $row_key;
		}
		else
		{
			dump($row_key);
			$this->_err="数据列不全";
			return false;
		}


		
		
		//print_r($row_key);
				
		//die();
	}

	/**
	 * 字符集转换
	 * @param  [type] $str [description]
	 * @return [type]      [description]
	 */
	
	protected function iconv_str($str)
	{
		return iconv("GBK","UTF-8",$str);
	}


	protected function saveNotFindCompany($row)
	{
		$data=F("NotFindCompany");
		$row_key=md5(implode(',',$row));
		if(!isset($data[$row_key]))
		{
			$data[$row_key]=$row;
			F("NotFindCompany",$data);
		}
	}


	public function noFindCompayLog()
	{
		$data=F("NotFindCompany");
		$file_key=date("ymdHis");
		$fp  =  fopen ( C("excel_file_path").$file_key.'.csv' ,  'w' );
		foreach($data as $row)
		{
			 fputcsv ( $fp ,  $row );
		}
		fclose ( $fp );
		F('NotFindCompany',NULL);
	}

	//对税收数据临时表中没有找到对应企业的数据进行模糊匹配
	public function upMssqlComid()
	{
		$md_revenue=D("Revenue");
		$md_comlist=D("ComList");
		$md_czjcom=D("CzjCom");
		$rows=$md_revenue->distinct(true)->field("nsrsbh")->where(array('mssql_comid'=>array('EXP','IS NULL')))->select();

		foreach($rows as $row)
		{
			$com_info=$md_comlist->where(array('nsrsbh'=>$row['nsrsbh']))->find();
			if(!empty($com_info['mssql_comid']))
			{
				$md_revenue->where(array('nsrsbh'=>$row['nsrsbh']))->save(array('mssql_comid'=>$com_info['mssql_comid']));
			}
			else
			{
				if(empty($com_info['sbh9_17'])) continue;
				$data=$md_czjcom->findByJgdmz($com_info['sbh9_17']);
				
				if(count($data)==0)
				{
					//echo ",未找到对应的企业;";
				}
				elseif(count($data)==1)
				{
					$mssql_cominfo=$data[0];
					//echo $com_info['nsrsbh'];
					echo "税收数据中,企业名称是:".$com_info['nsrmc'].",识别号是:".$com_info['nsrsbh'].";找到的相似企业名称为:".$mssql_cominfo['com_name'].",识别号:".$mssql_cominfo['com_nsrsbh'];
					echo "\r\n";
				}
				else
				{
					//echo ",找到多家企业;";
				}

				
			}
		}
	}

	//把可以处理的数据导入到Mssql里
	public function dataToMssql()
	{
		$md_revenue=D("Revenue");
		$md_ss=D("CzjSszsxx");
		$limit=10;
		$do_key=true;

		while ($do_key) {
			$rows=$md_revenue->where(array('state'=>$md_revenue::STATE_1,'mssql_comid'=>array('EXP','IS NOT NULL')))->limit($limit)->order("id")->select();

			if(empty($rows))
			{
				$do_key=false;
				continue;
			}
			foreach($rows as $row)
			{
				if($row['source']=='ds') $type=1;
				else $type=2;
				if($md_ss->addNewRow($type,$row))
				{
					$md_revenue->where(array('id'=>$row['id']))->save(array('state'=>$md_revenue::STATE_Over));
				}
			}
			unset($rows);
		}
	}
}